<template>
  <li :class="['todo-item', { completed: todo.completed }]">
    <input
      type="checkbox"
      :checked="todo.completed"
      @change="$emit('toggle-todo', todo.id)"
      class="todo-checkbox"
    />
    <input
      v-if="isEditing"
      v-model="editText"
      @keyup.enter="saveEdit"
      @blur="saveEdit"
      @keyup.esc="cancelEdit"
      class="todo-edit-input"
      ref="editInput"
    />
    <span
      v-else
      class="todo-text"
      @dblclick="startEdit"
    >
      {{ todo.text }}
    </span>
    <button @click="$emit('delete-todo', todo.id)" class="delete-btn">删除</button>
  </li>
</template>

<script setup>
import { ref, nextTick } from 'vue'

const props = defineProps({
  todo: {
    type: Object,
    required: true,
    validator: (value) => {
      return value && typeof value.id === 'number' && typeof value.text === 'string'
    }
  }
})

const emit = defineEmits(['toggle-todo', 'delete-todo', 'edit-todo'])

const isEditing = ref(false)
const editText = ref('')
const editInput = ref(null)

const startEdit = () => {
  isEditing.value = true
  editText.value = props.todo.text
  nextTick(() => {
    editInput.value?.focus()
  })
}

const saveEdit = () => {
  if (isEditing.value && editText.value.trim()) {
    emit('edit-todo', {
      id: props.todo.id,
      text: editText.value.trim()
    })
  }
  isEditing.value = false
}

const cancelEdit = () => {
  isEditing.value = false
  editText.value = ''
}
</script>

<style scoped>
.todo-item {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem;
  margin-bottom: 0.5rem;
  background-color: #f9f9f9;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.todo-item:hover {
  background-color: #f0f0f0;
}

.todo-item.completed .todo-text {
  text-decoration: line-through;
  color: #999;
}

.todo-checkbox {
  width: 20px;
  height: 20px;
  cursor: pointer;
}

.todo-text {
  flex: 1;
  font-size: 1.1rem;
}

.delete-btn {
  padding: 0.5rem 1rem;
  background-color: #f44336;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9rem;
}

.delete-btn:hover {
  background-color: #da190b;
}

.todo-edit-input {
  flex: 1;
  padding: 0.5rem;
  font-size: 1.1rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  outline: none;
}

.todo-edit-input:focus {
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}
</style>